﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections;
using System.Collections.Concurrent;

namespace SUNRPA.CONTROLS.IMPL.controls {
    /// <summary>
    /// TODO: 该控件有一个等待元素时间的参数。暂时不做这个功能，等之后再补齐，等待网页加载和元素加载
    /// </summary>
    public class ClickWebEleNAction : BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            ClickWebEleNParam? param = item.ControlParam as ClickWebEleNParam;
            WebElement ele = param.WebEle as WebElement;
            //判断是否为web元素
            if(ele == null){ 
                throw new RpaRuntimeException("元素不是web元素，无法进行web元素点击操作");
            }
            string webObject = param.WebObj;
            WebPage webPage = this.GetObjVar<WebPage>(ref webObject, globleData);
            if(webPage == null){ 
                throw new RpaRuntimeException("网页为空，无法进行web元素点击操作");
            }
            int clickType = param.ClickType;
            int buttonType = param.ButtonType;
            switch(webPage.Bt){ 
                case BrowserType.GOOGLE:
                    using(NamedPipeClientUtil client = new NamedPipeClientUtil("localhost"
                        , DefaultContents.NAMED_PIPE_SERVER, System.IO.Pipes.PipeDirection.InOut)) {
                        NamePipeRequest request = new NamePipeRequest();
                        request.method = DefaultContents.CLICK_ELE;
                        request.requestData = new Dictionary<string, object>() { { "tabId", webPage.TabId}, { "ele", ele }, { "clickType", clickType }, { "buttonType", buttonType } };
                        BridgeResponse resp = client.SendRequest(request);
                        if(!resp.code.Equals(CommunicationCode.OK)) {
                            throw new RpaRuntimeException($"点击web元素出错:{resp.msg}");
                        }
                    }
                    break;
                case BrowserType.IE:
                    break;
                case BrowserType.EDGE:
                    break;
                default:
                    throw new RpaRuntimeException("浏览器类型错误");
            }
            return currentIndex;
        }
    }
}
